package com.gengzp.rpc.interceptor;

import com.gengzp.rpc.context.RemoteTransactionalContextHolder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.UUID;

import static com.gengzp.rpc.constants.RemoteTransactionalConstants.REQUEST_ID_HEADER_KEY;

/**
 * @ClassName RpcRemoteTransactionalInterceptor
 * @Description
 * @Author gengzp
 * @Date 2025/8/11 19:57
 */
@Component
public class RpcRemoteTransactionalInterceptor implements HandlerInterceptor, Ordered {

    private static final Logger logger = LoggerFactory.getLogger(RpcRemoteTransactionalInterceptor.class);

    /**
     * 请求执行前的逻辑
     */
    @Override
    @SuppressWarnings("NullableProblems")
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断当前请求头中是否携带了唯一标识, 如果携带, 表示当前是远程调用, 则直接将唯一标识写入线程变量
        String requestId = request.getHeader(REQUEST_ID_HEADER_KEY);
        if (StringUtils.isBlank(requestId)) {
            // 当前请求未携带唯一标识, 表示是刚发起的本地调用, 此时生成一个唯一标识
            requestId = request.getRequestURI() + UUID.randomUUID().toString().replace("-", "");
        }

        // 将请求唯一标识写入线程变量, 供后续操作
        RemoteTransactionalContextHolder.setRequestId(requestId);
        return true;
    }


    @Override
    public int getOrder() {
        return 0;
    }
}
